package com.ds.iecs.im.processor;

import org.dom4j.Document;
import org.eclipse.jetty.websocket.api.Session;
import org.mx.notify.processor.WsMessageProcessor;
import org.mx.service.server.websocket.WsConnectKey;
import org.mx.service.server.websocket.WsSessionManager;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.alibaba.fastjson.JSONObject;
import com.ds.iecs.im.store.UserMappingList;

/**
 * WebSocket客户端登出消息处理器
 * 
 * @author john.peng
 *
 */
@Component("signOut")
public class SignOutMessageProcessor extends WsMessageProcessor {
	private static final Logger logger = LoggerFactory.getLogger(SignOutMessageProcessor.class);
	private static final String COMMAND_NAME = "signOut";
	private WsSessionManager wsSessionManager;
	private UserMappingList userMapping;

	/**
	 * 默认的构造函数
	 * 
	 * @param wsSessionManager WebSocket会话管理器
	 * @param userMapping      用户映射信息表
	 */
	@Autowired
	public SignOutMessageProcessor(WsSessionManager wsSessionManager, UserMappingList userMapping) {
		super(COMMAND_NAME);
		this.wsSessionManager = wsSessionManager;
		this.userMapping = userMapping;
	}

	@Override
	public boolean isMatched(JSONObject json) {
		try {
			JSONObject head = json.getJSONObject("head");
			return (COMMAND_NAME.equals(head.getString("command")));
		} catch (Exception ex) {
			if (logger.isWarnEnabled()) {
				logger.warn(String.format("Fetch json's field fail, json: %s.", json.toJSONString()), ex);
			}
			return false;
		}
	}

	@Override
	public boolean isMatched(Document xml) {
		throw new UnsupportedOperationException("The xml format message unsupported.");
	}

	@Override
	public boolean process(WsConnectKey connectKey, JSONObject json) {
		Session session = wsSessionManager.getSession(connectKey);
		if (session == null) {
			if (logger.isErrorEnabled()) {
				logger.error(String.format("The session['%s'] not found.", connectKey.toString()));
			}
			return false;
		}
		try {
			JSONObject head = json.getJSONObject("head");
			String userId = head.getString("userId");
			String system = head.getString("system");
			userMapping.signedOut(userId);
			JSONObject response = new JSONObject();
			JSONObject body = new JSONObject();
			body.put("command", COMMAND_NAME);
			body.put("userId", userId);
			body.put("system", system);
			response.put("body", body);
			response.put("code", 200);
			response.put("responseTime", System.currentTimeMillis());
			session.getRemote().sendString(response.toJSONString());
			return true;
		} catch (Exception ex) {
			if (logger.isErrorEnabled()) {
				logger.error(String.format("Process the message fail, message: %s.", json.toJSONString()));
			}
			return false;
		}
	}

	@Override
	public boolean process(WsConnectKey connectKey, Document xml) {
		throw new UnsupportedOperationException("The xml format message unsupported.");
	}

}
